/**
 * 
 */
package com.infodms.dms.actions.sales.marketmanage.costmanage;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jxl.Cell;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.sales.planmanage.PlanUtil.BaseImport;
import com.infodms.dms.actions.sales.planmanage.PlanUtil.ExcelErrors;
import com.infodms.dms.actions.sysmng.usemng.SgmDealerSysUser;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesCostImportDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesOrgCostImportDao;
import com.infodms.dms.dao.sales.planmanage.MonthPlanDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TcCodePO;
import com.infodms.dms.po.TmOrgPO;
import com.infodms.dms.po.TmVhclMaterialGroupPO;
import com.infodms.dms.po.TmpVsCostPO;
import com.infodms.dms.po.TmpVsDealerCostPO;
import com.infodms.dms.po.TmpVsHdCostPO;
import com.infodms.dms.po.TmpVsMonthlyPlanPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.csv.CsvWriterUtil;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.mvc.context.ResponseWrapper;


/**
 * @author yangpo
 *
 */
public class ActivitiesOrgCostImport extends BaseImport {

	public Logger logger = Logger.getLogger(SgmDealerSysUser.class);
	private final String implortUrl = "/jsp/sales/marketmanage/costmanage/activitiescostOrgImport.jsp";
	private final String checkSuccessUrl = "/jsp/sales/marketmanage/costmanage/activitiescostchecksuccess.jsp";
	private final String checkFailureUrl = "/jsp/sales/marketmanage/costmanage/activitiescostOrgcheckfailure.jsp";
	private final String importCompleteUrl = "/jsp/sales/marketmanage/costmanage/activitiescostOrgcomplete.jsp";
	private final String costTypes="市场推广费用,广告费用";
	private final String costSources="经销商费用,区域费用,总部费用";
	
	
	/**
	 * 初始使化导放页面
	 */
	public void activitiesCostImportInit() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			act.setForword(implortUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"未知错误!");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}

	/**
	 * 年度目标导入临时表
	 * 原有逻辑导入
	 */
	public void activitiesCostExcelOperate(){
		ActionContext act = ActionContext.getContext();
		RequestWrapper request = act.getRequest();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesOrgCostImportDao dao=ActivitiesOrgCostImportDao.getInstance();
		String areaId=request.getParamValue("areaId");
        try {
			TmpVsHdCostPO po=new TmpVsHdCostPO();//导入总部和区域临时表
        	
			//TmpVsCostPO po=new TmpVsCostPO();
			//TmpVsDealerCostPO po=new TmpVsDealerCostPO();
			//po.setUserId(logonUser.getUserId().toString());//删除当前登录账户的临时表
			//清空临时表中目标年度的数据
			dao.delete(po);
			long maxSize=1024*1024*5;//允许文件大小
			insertIntoTmp(request, "uploadFile",5,3,maxSize);//判断导入文件是否过大，数据是否正确。
			List<ExcelErrors> el=getErrList();//获取错误list  获取上面是否导入文件格式有错误
			if(null!=el&&el.size()>0){
				act.setOutData("errorList", el);
				act.setForword(checkFailureUrl);//返回错误信息页面
			}else{
				List<Map> list=getMapList();//获取正确数据
				//将数据插入临时表
				insertTmp(list, logonUser.getUserId(),areaId);//插入临时表
				//校验临时表数据
				List<ExcelErrors> errorList=checkData(logonUser.getUserId(),logonUser.getCompanyId().toString(),areaId);
				if(null!=errorList){
					act.setOutData("errorList", errorList);
					act.setForword(checkFailureUrl);
				}else{
					List<Map<String, Object>> tmpList=dao.selectDealerCostTmpTable(logonUser.getUserId());//导入临时表
					act.setOutData("planList", tmpList);
					act.setOutData("areaId", areaId);
					act.setForword(checkSuccessUrl);
				}
			}
			
		} catch (Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.BATCH_IMPORT_FAILURE_CODE,"文件读取错误");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	
	/*
	 * 把所有导入记录插入TMP_YEARLY_PLAN
	 */
	private void insertTmp(List<Map> list,Long userId,String areaId) throws Exception{
		if(null==list){
			list=new ArrayList();
		}
		for(int i=0;i<list.size();i++){
			Map map=list.get(i);//获取第一行map
			if(null==map){
				map=new HashMap<String, Cell[]>();
			}
			Set<String> keys=map.keySet();
			Iterator it=keys.iterator();
			String key="";
			while(it.hasNext()){
				key=(String)it.next();
				Cell[] cells=(Cell[])map.get(key);
				parseCells(key, cells, userId,areaId);
			}
		}
		
	}
	/*
	 * 每一行插入TMP_YEARLY_PLAN
	 * 数字只截取30位
	 */
	private void parseCellsOld(String rowNum,Cell[] cells,Long userId,String year,String month) throws Exception{
		    MonthPlanDao dao=new MonthPlanDao();
		    TmpVsDealerCostPO po=new TmpVsDealerCostPO();
		    po.setRowNumber(Long.parseLong(rowNum.trim()));
		    po.setDealerCode(subCell(cells[0].getContents().trim()));
		    po.setDealerName(subCell(cells[1].getContents().trim()));
		    po.setDealerAmount(subCell(cells[2].getContents().trim()));
//			TmpVsMonthlyPlanPO po=new TmpVsMonthlyPlanPO();
//			po.setRowNumber(rowNum.trim());
//			po.setOrgCode(subCell(cells[0].getContents().trim()));
//			po.setPlanYear(year.trim());
//			po.setPlanMonth(month);
//			po.setGroupCode(subCell(cells[1].getContents().trim()));
//			po.setSumAmt(subCell(cells[2].getContents().trim()));
//			po.setUserId(userId.toString());
			dao.insert(po);
	}
	/*
	 * 每一行插入TMP_YEARLY_PLAN（长安汽车）
	 * 数字只截取30位
	 * modify by wjb at 2010-08-18
	 * 增加列头：经销商名称（模板第2列）和车系名称（模板第4列），但不插入临时表
	 */
	private void parseCells(String rowNum,Cell[] cells,Long userId,String areaId) throws Exception{
		    ActivitiesCostImportDao dao=new ActivitiesCostImportDao();
		    TmpVsHdCostPO po=new TmpVsHdCostPO();
		   // TmpVsDealerCostPO po=new TmpVsDealerCostPO();
			//TmpVsCostPO po=new TmpVsCostPO();
		    System.out.println(Long.parseLong(rowNum.trim()));
			po.setRowNumber(Long.parseLong(rowNum.trim()));
			System.out.println(subCell(cells[1].getContents().trim()));
		    po.setOrgCode(subCell(cells[0].getContents().trim()));
		    po.setOrgName(subCell(cells[1].getContents().trim()));
		    po.setCostType(subCell(cells[2].getContents().trim()));
		    po.setCostDesc(subCell(cells[3].getContents().trim()));
		    po.setOrgAmount(subCell(cells[4].getContents().trim()));
		    po.setAreaId(Long.parseLong(areaId));
		    //po.setHdCode(subCell(cells[3].getContents().trim()));
			//po.setHdName(subCell(cells[4].getContents().trim()));
			//po.setHdAmount(subCell(cells[5].getContents().trim()));
			po.setUserId(userId.toString());
			dao.insert(po);
	}	
	/*
	 * 将输入字符截取最多30位
	 */
	private String subCell(String orgAmt){
		String newAmt="";
		if(null==orgAmt||"".equals(orgAmt)){
			return newAmt;
		}
		if(orgAmt.length()>30){
			newAmt=orgAmt.substring(0,30);
		}else{
			newAmt=orgAmt;
		}
		return newAmt;
	}
	/*
	 * 校验TMP_monthly_PLAN表中数据是否符合导入标准
	 */
	private List<ExcelErrors> checkData(Long userId,String companyId,String areaId){
		ActivitiesOrgCostImportDao dao=new ActivitiesOrgCostImportDao();
		TmpVsHdCostPO  orgPo=new TmpVsHdCostPO();
		orgPo.setUserId(userId.toString());
		//TmpVsCostPO planConPo=new TmpVsCostPO();
		//planConPo.setUserId(userId.toString());
		List<TmpVsHdCostPO>list=dao.select(orgPo);
		
		//List<TmpVsCostPO> list=dao.select(planConPo);
		if(null==list){
			list=new ArrayList();
		}
		
		ExcelErrors errors=null;
		TmpVsHdCostPO po=null;
		//TmpVsCostPO po=null;
		StringBuffer errorInfo=new StringBuffer("");//错误字符串
		boolean isError=false;//是否有错
		List<ExcelErrors> errorList = new ArrayList<ExcelErrors>();
		for(int i=0;i<list.size();i++){
			errors=new ExcelErrors();
			//取得TmpYearlyPlanPO
			po=list.get(i);
			//取得行号
			String rowNum=String.valueOf(po.getRowNumber());//获取该数据在第几行
			TmOrgPO MyOrgPo=new TmOrgPO();
			
			
			StringBuffer sql=new StringBuffer("");
			sql.append(" select * from tm_org tmo,tm_org_business_area toba\n");
			sql.append(" where tmo.org_id=toba.org_id\n");
			sql.append(" and  toba.area_id="+areaId+"\n");
			if(po.getOrgCode()!=null){
			sql.append(" and  tmo.org_code='"+po.getOrgCode()+"'\n");
			}
			List mylist=dao.pageQuery(sql.toString(),null,getFunName());
//			TmpVsHdCostPO HdCostPo1=new TmpVsHdCostPO();
//			HdCostPo1.setHdAmount(po.getHdAmount());
//			HdCostPo1.setHdCode(po.getHdCode());
//			HdCostPo1.setHdName(po.getHdName());
//			HdCostPo1.setOrgCode(po.getOrgCode());
//			HdCostPo1.setOrgName(po.getOrgName());
//			HdCostPo1.setOrgAmount(po.getHdAmount());
			List<TmOrgPO>list1=dao.select(MyOrgPo);
			if(mylist.size()<1){
				isError=true;
				errorInfo.append("组织不存在！,");
			}
			TcCodePO tcCodePo=new TcCodePO();
			tcCodePo.setCodeId(po.getCostType());
			List<TcCodePO>list2 =dao.select(tcCodePo);
			if(list2.size()<1){
				isError=true;
				errorInfo.append("该费用类型不存在！,");
			}
			
//			if(po.getHdCode()!=null&&po.getOrgCode()!=null){
//				isError=true;
//				errorInfo.append("区域和总部不能同时导入费用存在！,");
//			}
//			 List<Map<String, Object>> myList=dao.talbeCheckMyDealer(String.valueOf(userId), po.getDealerCode(),areaId);
//			if(myList.size()<1){
//				isError=true;
//				errorInfo.append("该经销商要属于当前业务范围并且属于整车销售！");
//			}
			//校验费用类型是否存在
			//if(costTypes.indexOf(po.getCostType())==-1){
			//	isError=true;
			//	errorInfo.append("费用类型不存在,");
			//}
			//校验费用来源是否存在
			//if(costSources.indexOf(po.getCostSource())==-1){
			//	isError=true;
			//	errorInfo.append("费用来源不存在,");
			//}
			//String dealerCode=CommonUtils.checkNull(po.getDealerCode());
			//String orgCode=CommonUtils.checkNull(po.getOrgCode());
			//if("".equals(dealerCode)&&"".equals(orgCode)){
			//	isError=true;
			//	errorInfo.append("经销商和组织不能同时为空,");
			//}
			//校验合计
//			try {
//				if(po.getHdAmount()!=""&&po.getHdAmount()!=null){
//				new Double(po.getHdAmount());
//				}
//			} catch (Exception e) {
//				isError=true;
//				errorInfo.append("组织资金必须是数字,");
//			}
			try {
				if(po.getOrgAmount()!=""&&po.getOrgAmount()!=null){
				new Double(po.getOrgAmount());
				}
			} catch (Exception e) {
				isError=true;
				errorInfo.append("组织资金必须是数字,");
			}
			if(errorInfo.length()>0){
				String info=errorInfo.substring(0,errorInfo.length()-1);
				errors.setRowNum(new Integer(rowNum));
				errors.setErrorDesc(info);
				errorList.add(errors);
				errorInfo.delete(0, errorInfo.length());
			}
		}
		//数据校验条件的MAP
//		Map<String, Object> conMap=new HashMap<String, Object>();
//		conMap.put("userId", userId);
//		conMap.put("companyId", companyId);
//
//		//校验经销商是否存在
//		List<Map<String, Object>> notExistsDlrList=dao.checkDlr(conMap);
//		if(null!=notExistsDlrList&&notExistsDlrList.size()>0){
//			for(int i=0;i<notExistsDlrList.size();i++){
//				Map<String, Object> map=notExistsDlrList.get(i);
//				isError=true;
//				ExcelErrors err=new ExcelErrors();
//				err.setRowNum(Integer.parseInt(map.get("ROW_NUMBER").toString()));
//				err.setErrorDesc("经销商代码不存在");
//				errorList.add(err);
//			}
//		}
//		//校验经组织是否存在
//		List<Map<String, Object>> notExistsOrgList=dao.checkOrg(conMap);
//		if(null!=notExistsOrgList&&notExistsOrgList.size()>0){
//			for(int i=0;i<notExistsOrgList.size();i++){
//				Map<String, Object> map=notExistsOrgList.get(i);
//				isError=true;
//				ExcelErrors err=new ExcelErrors();
//				err.setRowNum(Integer.parseInt(map.get("ROW_NUMBER").toString()));
//				err.setErrorDesc("组织代码不存在");
//				errorList.add(err);
//			}
//		}
//		//校验费用类型或来源
//		List<Map<String, Object>> wrongCostTypeSourceList=dao.checkTypeSource(conMap);
//		if(null!=wrongCostTypeSourceList&&wrongCostTypeSourceList.size()>0){
//			for(int i=0;i<wrongCostTypeSourceList.size();i++){
//				Map<String, Object> map=wrongCostTypeSourceList.get(i);
//				isError=true;
//				ExcelErrors err=new ExcelErrors();
//				err.setRowNum(Integer.parseInt(map.get("ROW_NUMBER").toString()));
//				err.setErrorDesc("导入了错误的费用类型或来源");
//				errorList.add(err);
//			}
//		}
		
		//临时表校验重复数据talbeCheckMyNuber
		//List<Map<String, Object>> dumpList=dao.talbeCheckDump(userId.toString());
		System.out.println(userId);
		List<Map<String, Object>> dumpList=dao.talbeCheckMyNuber(userId.toString());//判断是否重复数据
		if(null!=dumpList&&dumpList.size()>0){
			String r1="";
			String r2="";
			List<String> tmp=new ArrayList();
			String s1="";
			String s2="";
			for(int i=0;i<dumpList.size();i++){
				Map<String, Object> map=dumpList.get(i);
				r1=map.get("ROW_NUMBER1").toString();
				r2=map.get("ROW_NUMBER2").toString();
				s1=r1+","+r2;
				s2=r2+","+r1;
				if(tmp.contains(s1)||tmp.contains(s2)){
					continue;
				}else{
					isError=true;
					ExcelErrors err=new ExcelErrors();
					err.setRowNum(Integer.parseInt(r1));
					err.setErrorDesc("与"+r2+"行数据重复");
					errorList.add(err);
					tmp.add(s1);
				}
			}
		}
		if(isError){
			return errorList;
		}else{
			return null;
		}
	}
	/*
	 * 导入业务表
	 */
	public void importExcel(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesOrgCostImportDao dao=ActivitiesOrgCostImportDao.getInstance();
		try {
			
			RequestWrapper request=act.getRequest();
			String areaId=request.getParamValue("areaId");
			//数据校验条件的MAP
			
			Map<String, Object> conMap=new HashMap<String, Object>();
			conMap.put("userId", logonUser.getUserId().toString());
			conMap.put("companyId", logonUser.getCompanyId().toString());
			//dao.insertCost(conMap);
			dao.insertDealerCost(conMap,areaId);
			act.setForword(importCompleteUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	
	private Long getGroupId(String groupCode){
		MonthPlanDao dao=MonthPlanDao.getInstance();
		TmVhclMaterialGroupPO conPo=new TmVhclMaterialGroupPO();
		conPo.setGroupCode(groupCode);
		List<TmVhclMaterialGroupPO> groupList=dao.select(conPo);
		if(null==groupList||groupList.size()==0){
			return null;
		}else{
			return groupList.get(0).getGroupId();
		}
	}
	
	/**
	 * 市场活动费用导入模板下载
	 * @author zouchao
	 * @since  2010-08-20
	 */
	public void downloadTemple(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		ActivitiesOrgCostImportDao dao=ActivitiesOrgCostImportDao.getInstance();
		OutputStream os = null;
		try{
			ResponseWrapper response = act.getResponse();
			RequestWrapper request = act.getRequest();
			String areaId=request.getParamValue("areaId");
			//String dealerId=logonUser.getDealerId();
			String orgId=String.valueOf(logonUser.getOrgId());
			// 公司ID
			String companyId = CommonUtils.checkNull(logonUser.getCompanyId());
			
			// 用于下载传参的集合
			List<List<Object>> list = new LinkedList<List<Object>>();
			
			//标题
			List<Object> listHead = new LinkedList<Object>();
			listHead.add("组织代码");
			listHead.add("组织名称");
			listHead.add("费用类型编码");
			listHead.add("费用类型");
			//listHead.add("总部名称");
			//listHead.add("费用类型");
			//listHead.add("费用来源");
			listHead.add("资金数量");
			list.add(listHead);
			List<Map<String, Object>> orgSeriesList = dao.getTempDownOrgCompanyload(areaId);//查询所有的总部公司
			for(int i=0; i<orgSeriesList.size();i++){
				List<Object> listValue = new LinkedList<Object>();
				listValue.add(orgSeriesList.get(i).get("ORG_CODE") != null ? orgSeriesList.get(i).get("ORG_CODE") : "");
				listValue.add(orgSeriesList.get(i).get("ORG_NAME") != null ? orgSeriesList.get(i).get("ORG_NAME") : "");
				listValue.add(orgSeriesList.get(i).get("COST_TYPE") != null ? orgSeriesList.get(i).get("COST_TYPE") : "");
				listValue.add(orgSeriesList.get(i).get("COST_DESC") != null ? orgSeriesList.get(i).get("COST_DESC") : "");
				listValue.add(orgSeriesList.get(i).get("COST_AMOUNT") != null ? orgSeriesList.get(i).get("COST_AMOUNT") : "");
				list.add(listValue);
			}
//			List<Map<String, Object>> orgSeriesList1 = dao.getTempDownOrgload();//查询所有的总部公司
//			for(int i=0; i<orgSeriesList1.size();i++){
//				List<Object> listValue = new LinkedList<Object>();
//				listValue.add(orgSeriesList1.get(i).get("ORG_CODE") != null ? orgSeriesList1.get(i).get("ORG_CODE") : "");
//				listValue.add(orgSeriesList1.get(i).get("ORG_NAME") != null ? orgSeriesList1.get(i).get("ORG_NAME") : "");
//				listValue.add(orgSeriesList1.get(i).get("COST_AMOUNT") != null ? orgSeriesList1.get(i).get("COST_AMOUNT") : "");
//				listValue.add("");
//				listValue.add("");
//				listValue.add("");
//				list.add(listValue);
//			}
			
			
			// 导出的文件名
			String fileName = "总部区域市场活动费用导入模板.xls";
			// 导出的文字编码
			fileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
			response.setContentType("Application/text/xls");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			
			os = response.getOutputStream();
			//CsvWriterUtil.writeCsv(list, os);
			CsvWriterUtil.createXlsFile(list, os);
			os.flush();			
		}catch (Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.BATCH_IMPORT_FAILURE_CODE,"文件读取错误");
			logger.error(logonUser,e1);
			act.setException(e1);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public String getFunName() {
		StackTraceElement stack[] = new Throwable().getStackTrace(); 
		StackTraceElement ste = stack[1];   
		//System.out.println(ste.getClassName() + "." + ste.getMethodName() + ste.getLineNumber()); 
		StringBuilder strBuilder = new StringBuilder();
		return strBuilder.append(ste.getClassName()).
			append(".").append(ste.getMethodName()).
			append(ste.getLineNumber()).
			toString();  
	}
	
	
}
